<template>
    <!-- 整个就是弹窗组件 -->
    <el-dialog 
        class="create-group-dialog" 
        v-model="componentVisible" 
        title="创建群聊"
        :draggable="true"
        :modal="false"
        width="50%"
    >
        <div class="create-group-container">
            <!-- 左侧通讯录树区 -->
            <div class="left" ref="leftRef">

                <!-- 搜索框 -->
                <div class="search-box">
                    <el-input
                        clearable
                        placeholder="搜索"
                        :prefix-icon="Search"
                        v-model="treeKw"
                    />
                </div>

                <!-- 通讯录树 -->
                <div class="tree-box beautify-scrollbar">
                    <el-tree
                        ref="treeRef"
                        show-checkbox
                        node-key="id"
                        :data="treeData"
                        :highlight-current="true"
                        :expand-on-click-node="true"
                        :props="{label:'text',children:'childList',disabled:'disabled'}"
                        :default-expanded-keys="['01']"
                        :default-expand-all="false"
                        :filter-node-method="filterTree"
                        @check="handleCheck"
                        >
                        <!-- 自定义显示节点内容，node表示节点对象，data表示节点数据 -->
                        <template #default="{ node, data }">
                            <div class="custom-tree-node">
                                <div class="icon">
                                    <!-- 是部门节点就Folder图标 -->
                                    <el-icon v-if="data.nodeType === 1" :size="18"><Folder/></el-icon>
                                    <!-- 是用户节点就加头像 -->
                                    <lc-avatar class="lc-avatar" v-if="data.nodeType === 2" :src="data.val.avatar"/>
                                </div>
                                <div class="text">
                                    <!-- 节点名称 -->
                                    <div>{{ node.label }}</div>
                                </div>
                            </div>
                        </template>
                    </el-tree>
                </div>
                
            </div>

            <!-- 鼠标拖动捕捉区 -->
            <div class="resizer" @mousedown="startResize"></div>

            <!-- 右侧展示已选用户区 -->
            <div class="right">
                <div class="title">
                    <strong>已选择{{ selectedUserList.length }}个联系人</strong>
                </div>
                <div class="list beautify-scrollbar">
                    <div class="item" v-for="(item,index) in selectedUserList" :key="index">
                        <div class="user-info">
                            <lc-avatar class="lc-avatar" :src="item.val.avatar"/>
                            <span>{{ item.text }}</span>
                        </div>
                        <el-icon class="del-icon" @click="removeSelectedUser(item)"><Close/></el-icon>
                    </div>
                </div>
                
            </div>
        </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="componentVisible = false">取消</el-button>
          <el-button type="primary" @click="doSubmit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    
</template>

<script setup>
// 导入
import { ref,watch,defineProps,defineEmits,computed } from 'vue'
import { Search,Folder,UserFilled,Close } from '@element-plus/icons-vue';
import { $msg_e,$msg_s } from '../utils/msg.js'
import { $get,$post } from '../utils/request.js'
import { RoomApi, UserApi } from '@/api/path.js'
import LcAvatar from './LcAvatar.vue'
import { RoomState } from '@/store/currentRoom.js';
import { useRouter } from 'vue-router';


// 初始化
const router = useRouter()


// 数据
const treeData = ref([])
const treeKw = ref('')
const leftRef = ref(null)
const treeRef = ref(null)
const props = defineProps({
    // 是否可见
    visible:{
        type:Boolean,
        default:false
    },
    // 模式，create-创建群组，edit-编辑群成员
    mode:{
        type:String,
        default:''
    },
    // 添加成员下，传入的群中已有的联系人
    users:{
        type:Array,
        default:[]
    }
})
const emits = defineEmits({
    'update:visible':null,
    'update:mode':null
})

const componentVisible = computed({ // 计算属性可以让字段有响应式
    get: () => props.visible,
    set: (val) => {
        // 向父组件传递数据，在父组件中用v-model:visible绑定给一个响应式属性即可
        emits('update:visible', val);
    }
});
const existedUserIds = computed(() => {
    // includes使用===强等于，类型要一致
    return props.users.map(user => String(user.id))
})
const selectedUserMap = ref(new Map())
const selectedUserList = computed(() => {
    return Array.from(selectedUserMap.value.values())
})
let isResizing = false;
let initialWidth = 0;
let initialX = 0;

// 函数
const init = async () => {
    const res = await $get(UserApi.getContactBook);
    // console.log('init-getContactBook-res:',res);
    if(!res.success){
        return $msg_e(res.message)
    }
    treeData.value = res.data

    // edit模式下，对群中已有的用户设置禁选
    if(props.mode==='edit' && props.users.length > 0){
        // console.log('mode: ' + props.mode + ' , user: ' + JSON.stringify(props.users));
        // console.log('existedUserIds: ', existedUserIds.value);
        treeRef.value.setCheckedKeys(existedUserIds.value)
        setUserCheckDisable(treeData.value)
    }
    
}

const setUserCheckDisable = nodeList => {
    if(nodeList && nodeList.length > 0){
        nodeList.forEach(node => {
            if(node && node.nodeType===2 && existedUserIds.value.includes(node.id)){
                node.disabled = true
            }else{
                setUserCheckDisable(node.childList)
            }
        })
    }
}

const filterTree = (value, tree) => { // 过滤树
  if (!value) return true
  return tree.text.includes(value)
}


const handleCheck = () => {
    // 获取选中的节点
    const checkedNodes = treeRef.value.getCheckedNodes()
    // 过滤用户节点
    const checkedUserNodes = checkedNodes.filter(node => node.nodeType===2 && !existedUserIds.value.includes(node.id))
    // 存在map中
    selectedUserMap.value = new Map(checkedUserNodes.map(user => [user.id, user]))
}

const removeSelectedUser = data => {
    // 从map中删除
    selectedUserMap.value.delete(data.id)
    // 在tree中取消勾选
    treeRef.value.setChecked(data.id,false,false)
}


// 鼠标按下-开始拖拽宽度
const startResize = (e) => {
    isResizing = true;
    initialX = e.clientX; // 鼠标相对与浏览器左上角的x坐标
    initialWidth = leftRef.value.offsetWidth; // 获取元素的布局宽度（包括内边距、边框和垂直滚动条，但不包括外边距）
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', stopResize);
}

// 鼠标移动事件
const onMouseMove = (e) => {
    if (isResizing) {
        const deltaX = e.clientX - initialX;
        let newWidth = initialWidth + deltaX;
        // 限制最小宽度
        newWidth = newWidth < 150 ? 150 : (newWidth > 300 ? 300 : newWidth)
        leftRef.value.style.width = `${newWidth}px`;
    }
}

// 鼠标放开-停止拖拽宽度
const stopResize = () => {
    isResizing = false;
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', stopResize);
}

// 提交
const doSubmit = async () => {
    if(props.mode==='edit'){
        const addedUserIds = selectedUserList.value.map(user => user.id)
        if(!addedUserIds || addedUserIds.length === 0) return $msg_e('请选择联系人')
        const params = {
            roomId: RoomState.currentRoom.id,
            memberIds: addedUserIds
        }
        const res = await $post(RoomApi.addMember, params)
        console.log('addMember-res: ', res);
        if(!res.success){
            return $msg_e(res.message)
        }
        // 关闭弹框
        componentVisible.value = false
        // 重置编辑模式
        emits('update:mode', '');
    }else{
        const toUserIds = selectedUserList.value.map(user => user.id)
        if(!toUserIds || toUserIds.length === 0) return $msg_e('请选择联系人')
        const res = await $post(RoomApi.createRoom, toUserIds)
        console.log('createGroup-res: ', res);
        if(!res.success){
            return $msg_e(res.message)
        }
        RoomState.setCurrentRoom(res.data)
        // 关闭弹框
        componentVisible.value = false
        // 跳转到聊天界面
        router.push('/home/chat')
    }
}



// 侦听通讯录树搜索关键词执行过滤逻辑
watch(treeKw, newVal => {
  // console.log('treeKw-newVal:',newVal);
  if (treeRef.value) {
      // filter方法：接收一个参数并指定为 filter-node-method 属性的第一个参数
      treeRef.value.filter(newVal); // 直接访问，不使用非空断言
  }
})

// 侦听组件可视化componentVisible的变化执行初始化或数据清除逻辑
watch(
    () => componentVisible.value,
    (newVal) => {
        // console.log('watch-componentVisible: ' + newVal);
        if (newVal) {
            init();
        } else {
            treeData.value = []
            selectedUserMap.value.clear()
        }
    }
);


</script>

<style scoped lang="scss">
.create-group-container{
    height: 50vh; /**此处不要使百分比，%是相对于父元素计算的高度，vw、vh是相对于视口计算的 */
    display: flex;
    flex-direction: row;
    & > .left{
        width: 50%;
        padding: 5px;
        display: flex;
        flex-direction: column;
        & > .search-box{
            margin-bottom: 10px;
        }
        & > .tree-box{
            flex: 1;
            user-select: none; /**禁止DOM内容被选中及其兼容设置 */
            -webkit-user-select: none; /* Chrome, Safari */
            -moz-user-select: none; /* Firefox */
            -ms-user-select: none; /* Internet Explorer */
            & .custom-tree-node{
                font-size: 16px;
                display: flex;
                flex-direction: row;
                align-items: center;
                & > .icon{
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    & > .el-icon{
                        margin-right: 4px;
                        color: #3975C6;
                    }
                    & > .lc-avatar{
                        margin-right: 4px;
                    }
                }
                & > .text{
                    flex: 1;
                }
            }
        }
    }
    & > .right{
        flex: 1;
        background-color: #fff;
        padding: 10px 10px 10px 5px;
        display: flex;
        flex-direction: column;
        & > .title{
            font-size: 14px;
            margin-bottom: 10px;
        }
        & > .list{
            flex: 1;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            & > .item{
                margin-bottom: 10px;
                display: flex;
                flex-direction: row;
                justify-content: space-between;
                align-items: center;
                & > .user-info{
                    flex: 1;
                    display: flex;
                    flex-direction: row;
                    & > .lc-avatar{
                        margin-right: 4px;
                    }
                }
                & > .del-icon{
                    font-size: 18px;
                    cursor: pointer;
                }
            }
        }
    }
}
</style>